const express = require("express");
const router = express.Router();
const mysqlUtil = require('../utils/mysqlUtil');

// 分页查询
router.get('/page', async (req, res) => {
    // 获取并验证分页参数
    const page = Math.max(parseInt(req.query.page), 1) || 1; // 确保最小值为1
    const pageSize = Math.min(parseInt(req.query.pageSize), 50) || 10; // 设置最大pageSize为50，默认值为10
    const offset = (page - 1) * pageSize;
    
    const userid = req.query.userid; // 可选参数

    let totalSql = 'SELECT COUNT(*) AS total FROM dailyData';
    let listSql = 'SELECT * FROM dailyData';
    let params = [];

    // 动态添加WHERE条件
    if (userid) {
        totalSql += ' WHERE userid = ?';
        listSql += ' WHERE userid = ?';
        params.push(userid);
    }

    try {
        // 执行总记录数查询
        const totalResult = await mysqlUtil.query(totalSql, params.slice()); // 使用 slice 创建副本防止影响后续操作
        const total = totalResult[0].total;

        // 添加分页参数
        params.push(pageSize, offset); // LIMIT 和 OFFSET 参数放在最后
        const result = await mysqlUtil.query(`${listSql} LIMIT ? OFFSET ?`, params);
        console.log(result)
        res.json({
            status: true,
            message: '查询成功',
            data: result,
            page: page,
            pageSize: pageSize,
            total: total,
            code: '200'
        });
    } catch (error) {
        console.error('Error occurred during query:', error); // 更详细的错误日志
        res.status(500).json({
            status: false,
            message: '查询失败',
            error: error.message,
            code: '500'
        });
    }
});

//新增
router.post('/add', async (req, res) => {
    const { foodin, userid, weight, time, drink, waist, sleep } = req.body;

    // 构建要插入的字段名和值数组
    const fields = [];
    const values = [];

    if (foodin !== undefined && foodin !== null) {
        fields.push('foodin');
        values.push(foodin);
    }
    if (userid !== undefined && userid !== null) {
        fields.push('userid');
        values.push(userid);
    }
    if (weight !== undefined && weight !== null) {
        fields.push('weight');
        values.push(weight);
    }
    if (waist !== undefined && waist !== null) {
        fields.push('waist');
        values.push(waist);
    }
    if (sleep !== undefined && sleep !== null) {
        fields.push('sleep');
        values.push(sleep);
    }
    if (drink !== undefined && drink !== null) {
        fields.push('drink');
        values.push(drink);
    }
    if (time !== undefined && time !== null) {
        fields.push('time');
        values.push(time);
    }

    // 如果没有任何字段提供，则返回错误信息
    if (fields.length === 0) {
        return res.status(400).json({
            status: false,
            message: '至少需要提供一个字段'
        });
    }

    // 动态构建 SQL 插入语句
    const sql = `INSERT INTO dailyData (${fields.join(', ')}) VALUES (${fields.map(() => '?').join(', ')})`;

    try {
        const result = await mysqlUtil.query(sql, values);
        res.json({
            status: true,
            message: '新增成功',
            data: {
                id: result.insertId
            },
            code: '200'
        });
    } catch (error) {
        console.error(error); // 记录错误日志以便调试
        res.status(500).json({
            status: false,
            message: '服务器内部错误',
            error: error.message
        });
    }
});

// 删除指定ID的
router.delete('/delete/:id', async (req, res) => {
    const id = req.params.id;

    // 检查 id 是否有效
    if (!id || isNaN(id)) {
        return res.status(400).json({
            status: false,
            message: '无效的每日数据ID'
        });
    }

    try {
        const result = await mysqlUtil.query('DELETE FROM dailyData WHERE id = ?', [id]);
        if (result.affectedRows === 0) {
            return res.status(404).json({
                status: false,
                message: '未找到要删除的数据'
            });
        }
        res.json({
            status: true,
            message: '删除成功',
            data: {
                affectedRows: result.affectedRows
            },
            code: '200'
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: false,
            message: '服务器内部错误',
            error: error.message
        });
    }
});

//修改
router.put('/update', async (req, res) => {
    const { id, foodin, userid, weight, time } = req.body;

    // 检查 id 是否存在
    if (!id) {
        return res.status(400).json({
            status: false,
            message: '每日数据 ID 不能为空'
        });
    }

    // 构建更新字段
    const updateFields = [];
    const values = [];

    if (foodin !== undefined && foodin !== null) {
        updateFields.push('foodin = ?');
        values.push(foodin);
    }
    if (userid !== undefined && userid !== null) {
        updateFields.push('userid = ?');
        values.push(userid);
    }
    if (weight !== undefined && weight !== null) {
        updateFields.push('weight = ?');
        values.push(weight);
    }
    if (time !== undefined && time !== null) {
        updateFields.push('time = ?');
        values.push(time);
    }

    // 如果没有要更新的字段，直接返回成功
    if (updateFields.length === 0) {
        return res.json({
            status: true,
            message: '无需更新任何字段'
        });
    }

    // 构建 SQL 查询
    const sql = `UPDATE dailyData SET ${updateFields.join(', ')} WHERE id = ?`;
    values.push(id);

    try {
        const result = await mysqlUtil.query(sql, values);
        if (result.affectedRows === 0) {
            return res.status(404).json({
                status: false,
                message: '未找到要更新的数据'
            });
        }
        res.json({
            status: true,
            message: '修改成功',
            data: {
                affectedRows: result.affectedRows
            },
            code: '200'
        });
    } catch (error) {
        console.error(error); // 记录错误日志以便调试
        res.status(500).json({
            status: false,
            message: '服务器内部错误',
            error: error.message
        });
    }
});

module.exports = router;